package com.shuogesha.bean;

import java.util.concurrent.Callable;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
/**
 * 自定义的hystrix 线程策略, 将servletRequestAttributes传入新线程中，并赋给RequestContextHolder:
 * @author zhaohaiyuan
 *
 */
public class MyHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
	@Override
	public <T> Callable<T> wrapCallable(Callable<T> callable) {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		return new Callable<T>() {
			@Override
			public T call() throws Exception {
				try {
					if (null != servletRequestAttributes) {
						RequestContextHolder.setRequestAttributes(servletRequestAttributes);
					}
					return callable.call();
				} finally {
					RequestContextHolder.resetRequestAttributes();
				}
			}
		};
	}
}
